package com.smasher.nfc

import android.Manifest
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.nfc.NfcAdapter
import android.nfc.tech.IsoDep
import android.nfc.tech.MifareClassic
import android.nfc.tech.MifareUltralight
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.nfc.tech.NfcA
import android.nfc.tech.NfcB
import android.nfc.tech.NfcF
import android.nfc.tech.NfcV
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

abstract class NFCConfig : AppCompatActivity() {

    // NFC
    var mNfcAdapter: NfcAdapter? = null

    // 添加 permissionLauncher 来处理权限请求结果
    private val permissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                setupNfc()
            } else {
                Toast.makeText(this, "NFC 权限被拒绝，请在设置中手动开启", Toast.LENGTH_SHORT).show()
                // 引导用户手动开启权限
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 检查 NFC 权限
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.NFC
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // 请求 NFC 权限
            permissionLauncher.launch(Manifest.permission.NFC)
            return
        }

        setupNfc()
    }

    // 将 NFC 初始化逻辑提取到 setupNfc 方法中
    private fun setupNfc() {
        val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (nfcAdapter == null) {
            Toast.makeText(this, "该设备不支持NFC，请检查硬件", Toast.LENGTH_SHORT).show()
        } else {
            if (!nfcAdapter.isEnabled) {
                val setNfc = Intent(Settings.ACTION_NFC_SETTINGS)
                startActivity(setNfc)
            }
            // NFC 初始化设置
            mNfcAdapter = nfcAdapter
        }
    }

    override fun onResume() {
        super.onResume()
        // 开启前台调度系统
        mNfcAdapter?.enableForegroundDispatch(
            this,
            createPendingIntent(),
            IntentFilterArray,
            TechListArray
        )
    }

    override fun onPause() {
        // 关闭前台调度系统
        mNfcAdapter?.disableForegroundDispatch(this)
        super.onPause()
    }

    // 创建 PendingIntent 的方法
    private fun createPendingIntent(): PendingIntent {
        val flag = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            PendingIntent.FLAG_MUTABLE
        } else {
            0
        }
        val intent = Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        return PendingIntent.getActivity(this, 0, intent, flag)
    }

    companion object {

        private val IntentFilterArray = arrayOf(
            IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED).apply {
                addDataType("*/*")
            },
            IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED),
            IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        )

        private val TechListArray = arrayOf(
            arrayOf(
                IsoDep::class.java.name,
                NfcA::class.java.name,
                NfcB::class.java.name,
                NfcF::class.java.name,
                NfcV::class.java.name,
                Ndef::class.java.name,
                NdefFormatable::class.java.name,
                MifareClassic::class.java.name,
                MifareUltralight::class.java.name
            )
        )
    }
}